package com.study.login;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.study.entity.User;
import com.study.service.IUserService;
import com.study.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private static final Log log = LogFactory.get();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("name");
        String password = request.getParameter("password");

        log.info("登录用户【{}】,登录密码【{}】",name,password);

        //判断用户是否提交了账号密码
        if (StrUtil.isBlankIfStr(name) || StrUtil.isBlankIfStr(password)){
            request.setAttribute("message","账号或者密码不能为空!");
            request.getRequestDispatcher("/fail.jsp").forward(request,response);
            return;
        }

        //查询账号是否存在
        IUserService userService = new UserServiceImpl();
        User user = userService.selectUserByUserName(name);

        if (user == null){
            request.setAttribute("message","账号不存在,请先注册!");
            request.getRequestDispatcher("/fail.jsp").forward(request,response);
            return;
        }

        //判断账号密码是否正确
        if (!user.getUserName().equals(name) || !user.getUserPassword().equals(password)){
            request.setAttribute("message","账号或者密码错误!");
            request.getRequestDispatcher("/fail.jsp").forward(request,response);
            return;
        }

        //账号密码正确,跳转到成功页面
        request.setAttribute("message","登录成功!");
        request.getRequestDispatcher("/success.jsp").forward(request,response);

    }
}
